/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.wechat.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.github.sd4324530.fastweixin.api.OauthAPI;
import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import com.github.sd4324530.fastweixin.api.enums.OauthScope;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.OauthGetTokenResponse;
import com.thinkgem.jeesite.common.config.GlobalConst;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.modules.wechat.custom.MyOauthAPI;
import com.thinkgem.jeesite.modules.wechat.config.WxMpConfig;

/**
 * 微信oauth拦截器
 * @author waile23
 * @version 2017-10-23
 */
public class Oauth2Interceptor extends BaseService implements HandlerInterceptor {
	@Autowired
	private WxMpConfig wxConfig;
	
	//private static final String TOKEN = "MYWEIXINTOKEN";
    //private static final String APP_ID = "wx58b99d4578cf6f1b";
    //private static final String APP_SECRET = "fd2a8528bc20a6c6990196609f76c527";
	/**
	 * 拦截器
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler) throws Exception {
		//如果使用session时，判断缓存中是否存在内容，如果存在则通过
		if(CacheUtils.get(GlobalConst.WECHAT_USER_CACHE, request.getSession().getId()) != null) {
			return true;
		}
		
		String queryString = "";
		if (request.getQueryString() != null) {
			queryString = "?" + request.getQueryString().toString();
		}
		
		String url = request.getRequestURL().toString();
		//获得oauth2buildAuthorizationUrl返回的Code
		String code = request.getParameter("code");
		//将Code放入缓存，如果该Code已经使用则不再使用(防止code被多次使用)
		if (code != null && CacheUtils.get(GlobalConst.WECHAT_OAUTH_CACHE, code) != null) {
			return true;
		}
		
		if (code != null) {
			//2.如果code不为空，那么则为redirect的请求，取得微信用户信息保存到session中
			//当用户同意授权后，会回调所设置的url并把authorization code传过来，然后用这个code获得access token
			//WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxService.oauth2getAccessToken(code);
			ApiConfig config = new ApiConfig(this.wxConfig.getAppid(), this.wxConfig.getAppsecret());
	    	MyOauthAPI oauthAPI = new MyOauthAPI(config);
	    	OauthGetTokenResponse token=oauthAPI.getToken(code);
			//刷新access token
			//wxMpOAuth2AccessToken = wxService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
	    	
			//3.获得用户基本信息
			//WxMpUser wxMpUser = wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
			GetUserInfoResponse userInfo=oauthAPI.getUserInfo(token.getAccessToken(), token.getOpenid());
			
			//将Code放入缓存，如果该Code已经使用则不再使用(防止code被多次使用)
			CacheUtils.put(GlobalConst.WECHAT_OAUTH_CACHE, code, code);
			//将wxMpUser存入缓存中，key为sessionId
			CacheUtils.put(GlobalConst.WECHAT_USER_CACHE, request.getSession().getId(), userInfo);
			return true;
		}
		ApiConfig config = new ApiConfig(this.wxConfig.getAppid(), this.wxConfig.getAppsecret());
		//1.首先构造网页授权url，然后构成超链接让用户点击 （当Code为空时调用）
		//url = wxService.oauth2buildAuthorizationUrl(url + queryString, OAuth2Scope.SNSAPI_USERINFO, null);
		OauthAPI oauthAPI = new OauthAPI(config);
		url=oauthAPI.getOauthPageUrl(url + queryString, OauthScope.SNSAPI_USERINFO, "1");
		response.sendRedirect(url);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
			Object handler, Exception ex) throws Exception {
		
	}

}
